"use client"
import { Tree, Input, Button, Space } from 'antd';
import { Menu, Item, useContextMenu } from 'react-contexify';
import './ReactContexify.min.css';
import { useState, useMemo } from 'react'
import type { TreeDataNode } from 'antd';
const { Search } = Input;

type TreeRightProps = {
    dataSource: any[];
    contextMenu: any;
    onSelect: (selectedKeys: any, info: any) => void;
};
const getParentKey = (key: string, tree: TreeDataNode[]): React.Key => {
    let parentKey: React.Key;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some((item) => item.title === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey!;
};
const expandAllArr: string[] = []
const TreeRight: React.FC<TreeRightProps> = (props) => {
    const { dataSource, contextMenu, onSelect } = props;
    const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
    const [searchValue, setSearchValue] = useState('');
    const [autoExpandParent, setAutoExpandParent] = useState(true);

    const dataList: { key: React.Key; title: string }[] = [];
    const generateList = (data: TreeDataNode[]) => {
        for (let i = 0; i < data.length; i++) {
            const node = data[i];
            const { key, title } = node;
            dataList.push({ key, title: title as string });
            if (node.children) {
                expandAllArr.push(node.key.toString())
                generateList(node.children);
            }
        }
    };
    generateList(dataSource);
    const treeData = useMemo(() => {
        const loop = (data: TreeDataNode[]): TreeDataNode[] =>
            data.map((item) => {
                const strTitle = item.title as string;
                const index = strTitle.indexOf(searchValue);
                const beforeStr = strTitle.substring(0, index);
                const afterStr = strTitle.slice(index + searchValue.length);
                const title =
                    index > -1 ? (
                        <span key={item.key}>
                            {beforeStr}
                            <span className="site-tree-search-value">{searchValue}</span>
                            {afterStr}
                        </span>
                    ) : (
                        <span key={item.key}>{strTitle}</span>
                    );
                if (item.children) {
                    return { title, key: item.key, children: loop(item.children) };
                }

                return {
                    title,
                    key: item.key,
                };
            });
        return loop(dataSource);
    }, [searchValue]);
    // 右键菜单
    const ContextMenu = () => (
        <Menu id={contextMenu.menuId}>
            {contextMenu.items.map((item: any) => (
                // 这里需要加key，不然要报错
                <Item key={item.key} onClick={item.handler}>{item.name}</Item>
            ))}
        </Menu>
    );

    const { show } = useContextMenu({
        id: contextMenu.menuId
    });
    const onExpand = (newExpandedKeys: React.Key[]) => {
        setExpandedKeys(newExpandedKeys);
        setAutoExpandParent(false);
    };
    // 右键显示菜单
    const handleContextMenu = (event: any, node: any) => {
        event.preventDefault();
        show({
            event,
            props: node
        });
    }
    const onChange = (e: any) => {
        const { value } = e.target;
        const newExpandedKeys = dataList
            .map((item) => {
                if (item.title.indexOf(value) > -1) {
                    return getParentKey(item.title, dataSource);
                }
                return null;
            }).filter((item, i, self): item is React.Key => !!(item && self.indexOf(item) === i));
        setExpandedKeys(newExpandedKeys);
        setSearchValue(value);
        setAutoExpandParent(true);
    };
    const onSearch = (value: string) => {
        const newExpandedKeys = dataList
            .map((item) => {
                if (item.title.indexOf(value) > -1) {
                    return getParentKey(item.title, dataSource);
                }
                return null;
            }).filter((item, i, self): item is React.Key => !!(item && self.indexOf(item) === i));
        setExpandedKeys(newExpandedKeys);
        setSearchValue(value);
        setAutoExpandParent(true);
    };
    const expandAll = () => {
        setExpandedKeys(expandAllArr)
    }
    const expandNone = () => {
        setExpandedKeys([])
    }
    const addLevel0 = () => { }
    return (
        <div>
            <div style={{ margin: '0px 0px 12px' }}>
                <Space.Compact style={{ width: '100%' }}>
                    <Input defaultValue="" placeholder='请输入' />
                    <Button type="primary">保存</Button>
                </Space.Compact>
            </div>
            <div style={{ margin: '0px 0px 12px' }}>
                <Button size='small' type="primary" onClick={expandAll}>一键展开</Button>
                <Button size='small' style={{ margin: '0 12px' }} type="primary" onClick={expandNone}>一键收起</Button>
            </div>
            <Search style={{ marginBottom: 8 }} placeholder="Search" onPressEnter={onChange} onSearch={onSearch} />
            <Tree
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                defaultExpandAll
                treeData={treeData}
                onSelect={onSelect}
                // 右键事件
                onRightClick={({ event, node }: any) => {
                    handleContextMenu(event, node)
                }}
            />
            <ContextMenu />
        </div>
    );
};

export default TreeRight;